const router = require('express').Router()
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')
const validateToken = require('../../../common/validateToken')

router.get('/getRoleListTotal', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  // 通过 ---------------------------------------------------------------

  const { page_index, page_size } = req.query // page_index页码  page_size页大小
  if (
    !Bee.StringUtils.isNotBlank(page_index) ||
    !Bee.StringUtils.isNotBlank(page_size)
  )
    return handleError(10003, '参数错误')

  const params = [
    (parseInt(page_index) - 1) * parseInt(page_size),
    parseInt(page_size),
  ]

  // 查询全部用户信息
  const [selectRoleError, roleList] = await to(
    db.query('SELECT * FROM role limit ?,?', params)
  )
  if (selectRoleError || !roleList) return handleError(-1, selectRoleError)

  // 查询用户信息数据总条数
  const [selectRoleTotalError, roleTotal] = await to(
    db.query('SELECT count(*) as total FROM role')
  )
  if (selectRoleTotalError || !roleTotal)
    return handleError(-1, selectRoleTotalError)

  let total = roleTotal[0]['total']
  resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      list: roleList,
      total: total,
    },
  })
})

module.exports = router
